﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HBAClient
{
    public partial class Report : Form
    {
        public Report()
        {
            InitializeComponent();
        }

		private void Report_Load(object sender, EventArgs e)
		{
			HBADBDataContext db = new HBADBDataContext();

			var query = from balance in db.Balances
						join bank in db.Banks on balance.BankID equals bank.BankID
						where balance.UserID == Program.GetUserID()
						select new { BankName = bank.BankName, 
									 BankID   = bank.BankID };

			//dgvReport.DataSource = query.Distinct();
			cmbBank.DisplayMember = "BankName";
			cmbBank.ValueMember = "BankID";
			cmbBank.DataSource = query.Distinct();

			var query2 = from bill in db.Bills
						 where bill.UserID == Program.GetUserID()
						 select new
						 {
							 Source = bill.Source
						 };

			cmbSource.DisplayMember = "Source";
			cmbSource.ValueMember = "Source";
			cmbSource.DataSource = query2.Distinct();

		}

		private void CheckDateValidation()
		{
			if (dtEndDatePick.Value.Date < dtStartDatePick.Value.Date)
			{
				MessageBox.Show("End Date cannot be earlier than Start Date");
				dtStartDatePick.Value = DateTime.Now.Date;
				dtEndDatePick.Value = DateTime.Now.Date;
			}
		}

		private void btnRun_Click(object sender, EventArgs e)
		{

			HBADBDataContext db = new HBADBDataContext();

			var query = from bill in db.Bills
						join bank in db.Banks on bill.BankID equals bank.BankID
						where bill.UserID == Program.GetUserID() && 
						bill.Date >= dtStartDatePick.Value.Date &&
						bill.Date <= dtEndDatePick.Value.Date.AddDays(1) &&
						bill.Source.Contains(cmbSource.Text) &&
						bank.BankID.ToString() == Convert.ToString(cmbBank.SelectedValue)
						select new
						{
							BillID = bill.BillID,
							BankName = bank.BankName,
							Date = bill.Date,
							Source = bill.Source,
							InSum = bill.InSum,
							OutSum = bill.OutSum,
							Balance = bill.Balance
						};

			try
			{
				dgvReport.DataSource = query;
			}
			catch (Exception ex)
			{
				dgvReport.DataSource = null;
			}
			
		}


		private void dtStartDatePick_CloseUp(object sender, EventArgs e)
		{
			CheckDateValidation();
		}

		private void dtEndDatePick_ValueChanged(object sender, EventArgs e)
		{
			CheckDateValidation();
		}

		private void dtEndDatePick_CloseUp(object sender, EventArgs e)
		{
			CheckDateValidation();
		}

        private void brnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
